/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ssdd.utilities;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jheorge
 */
public class Conection extends Thread {

    Socket s = null;
    private DataInputStream dis;
    private DataOutputStream dos;
    private boolean authenticate = false;
    private boolean haveUserList = false;
    private boolean itsAlive = true;

    public boolean isItsAlive() {
	return itsAlive;
    }

    public void setItsAlive(boolean itsAlive) {
	this.itsAlive = itsAlive;
    }

    //crea una nueva instancia de Conexion
    public Conection(Socket s) {
	try {
	    dis = new DataInputStream(s.getInputStream());
	    dos = new DataOutputStream(s.getOutputStream());
	    start();
	} catch (Exception e) {
	}
    }

    public String sendLoginMessage(String userName, String password) {
	String msg = null;
	String response = null;
	System.out.println("Enviando autenticacion...");
	if (userName != null && userName.length() > 0 && password != null && password.length() > 0) {
	    msg = "LG#$#" + userName + "#$#" + password;
	    sendMessage(msg);
	    System.out.println("esperando respuesta ......");
	    while (response == null) {
		try {
		    String sMessage = dis.readUTF();
		    System.out.println(" sendLoginMessage respuesta :::: " + sMessage);
		    StringTokenizer token = new StringTokenizer(sMessage, "#$#");
		    String codigo = token.nextToken();
		    if (codigo.equals("LG")) {
			response = token.nextToken();
		    }
		} catch (IOException ex) {
		    response = "ERROR EN LA CONEXION";
		    ex.printStackTrace();
		}
	    }
	    if (response.equals("VALID")) {
		authenticate = true;
	    }
	    System.out.println("[sendLoginMessage] flag : " + authenticate);
	}
	return response;
    }

    public List<String> reciveAllUsersConnected(String user) {
	List users = null;
	System.out.println("solicitando lista de usuarios");
	sendMessage("UC#$#" + user);
	while (users == null) {
	    try {
		if (authenticate) {
		    String sMessage = dis.readUTF();
		    System.out.println(" reciveAllUsersConnected respuesta :::: " + sMessage);
		    StringTokenizer token = new StringTokenizer(sMessage, "#$#");
		    String codigo = token.nextToken();
		    if (codigo.equals("UC")) {
			users = new ArrayList<String>();
			while (token.hasMoreTokens()) {
			    users.add(token.nextToken());
			}
		    }
		}
	    } catch (IOException ex) {
		ex.printStackTrace();
	    }
	}
	haveUserList = true;
//	if (users != null && !users.isEmpty()) {
//	    haveUserList = true;
//	}
	System.out.println("[reciveAllUsersConnected] flag : " + haveUserList);
	return users;
    }

    public String sendMessage(String message, String userName, List<String> destUsers) {
	String msg = null;
	if (message != null && message.length() > 0 && destUsers != null && !destUsers.isEmpty()) {
	    msg = "MSG#$#" + message + "#$#" + userName;
	    for (String dUser : destUsers) {
		msg = msg + "#$#" + dUser;
	    }
	    System.out.println("[CLIENTE][" + userName + "] sendMessage: " + msg);
	    sendMessage(msg);
	}
	return msg;
    }

    @Override
    public void run() {
	while (itsAlive) {
	    try {
		if (authenticate && haveUserList) {
		    String sMessage = dis.readUTF();
		    System.out.println(" run() respuesta :::: " + sMessage);
		    StringTokenizer token = new StringTokenizer(sMessage, "#$#");
		    String codigo = token.nextToken();
		    if (codigo.equals("MSG")) {
			System.out.println("[CLIENTE] mensaje MSG:" + sMessage);
			String message = token.nextToken();
			System.out.println("[CLIENT] menssage :" + message);
			String userOwn = token.nextToken();
			System.out.println("[CLIENT] userOwn :" + userOwn);
			//buscando identificador de frame del chat en el cual se visualizara el mensaje		
			String tmp = sMessage.substring(sMessage.indexOf("#$#") + 3, sMessage.length());
			System.out.println("corte 1 :: " + tmp);
			tmp = tmp.substring(tmp.indexOf("#$#") + 3, tmp.length());
			System.out.println("corte 2 :: " + tmp);
//			tmp = tmp.substring(tmp.indexOf("#$#") + 3, tmp.length());
//			System.out.println("corte 3 :: " + tmp);
			System.out.println("Frame identifier : " + tmp);
			ConectionManager.getInstance().updateChatFrame(message, userOwn, tmp);
		    } else if (codigo.equals("UC")) {
			System.out.println("actualizando lista");
			List<String> users = new ArrayList<String>();
			while (token.hasMoreTokens()) {
			    users.add(token.nextToken());
			}
			ConectionManager.getInstance().updatePrincipalFrame(users);
		    }else if (codigo.equals("LGO")){
			String user = token.nextToken();
			ConectionManager.getInstance().logout(user);
		    }

		}
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
    }

    public void sendLogoutMessage( String user) {
	sendMessage("LGO#$#" + user);
    }

    private void sendMessage(String message) {
	try {
	    System.out.println(" enviando mensaje : " + message);
	    dos.writeUTF(message);
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}
